package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaohe.common.R;
import com.gaohe.pojo.User;
import com.gaohe.service.UserService;
import com.gaohe.utils.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    HttpServletRequest request;

    //发送验证码
    @PostMapping("/sendMsg")
    public R sendCode(@RequestBody User user, HttpServletRequest request) {
        //生成验证码
        String code = CodeUtils.generateValidateCode4String(4);
        //存入session中
        request.getSession().setAttribute("code", code);
        return R.success(code);
    }

    //登录操作
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        //查询用户信息
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(user.getPhone() != null, User::getPhone, user.getPhone());
        User one = userService.getOne(lqw);
        //判断用户是否存在
        if (one != null) {
            Object code = session.getAttribute("code");
            //判断验证码是否正确
            if (user.getCode().equals(code)) {
                //用户已经注册，验证码也正确，存入session中
                session.setAttribute("user", one);
                return R.success("登陆成功");
            } else {
                return R.error("验证码错误");
            }
        } else {
            return R.error("用户未注册");
        }
    }

    //登出操作
    @PostMapping("/loginout")
    public R<String> logout() {
        request.getSession().setAttribute("user", null);
        return R.success("");
    }
}
